// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const usersDb = cloud.database().collection('users')
  const userData = await usersDb.where({
    openid
  }).get()
  const user = userData.data[0]
  const newBooks = []
  // 用户中移除归还一项
  user.books.forEach(item => {
    if (item.bookId !== event.bookId) {
      newBooks.push(item)
    }
  })
  user.books = newBooks

  // 书籍中移除 owners
  const booksDb = cloud.database().collection('books')
  const bookData = await booksDb.where({
    bookId: event.bookId
  }).get()
  const book = bookData.data[0]
  const newOwners = []
  book.owners.forEach(item => {
    if (user._id !== item) {
      newOwners.push(item)
    }
  })
  delete book._id
  book.remain++
  book.status = true
  book.owners = newOwners
  await booksDb.where({
    bookId: event.bookId
  }).update({
    data: book
  })
  delete user._id
  user.bookCount -= 1
  if (user.bookCount === 0) {
    user.status = 0
  }
  await usersDb.where({
    openid
  }).update({
    data: user
  })
  return {
    status: 0,
    msg: '归还成功'
  }
}